package com.gph.saviorframework.security.web.controller;

import com.gph.saviorframework.security.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by savior on 2016/3/8.
 */
@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/dologin",method = RequestMethod.POST)
    public void login(
            @RequestParam(value = "loginType")String loginType,
            @RequestParam(value = "username")String username,
            @RequestParam(value = "password")String password,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        try {
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(username,password);
            token.setRememberMe(false);

            subject.login(token);
            Session session = subject.getSession();
            session.setAttribute("_CURRENT_USER_", userService.get(username));
            session.setAttribute("_USERNAME_", username);

            response.sendRedirect(request.getContextPath() + "/admin");
        }
        catch (Exception ex){
            ex.printStackTrace();
            response.sendRedirect(request.getContextPath() + "/login?error='"+ex.getMessage()+"'");
        }
    }

    @RequestMapping(value = "/dologout",method = RequestMethod.GET)
    public void logout(){
        try {
            SecurityUtils.getSubject().logout();
        }
        catch (Exception ex){
            ex.printStackTrace();
        }
    }
}
